package com.ymt.reliable.message.queue.rabbitmq.service.impl;

import com.ymt.reliable.message.exception.TransactionMessageException;
import com.ymt.reliable.message.queue.service.MessageQueueService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;

/**
 * 基于 RabbitMq 实现
 */
@Service
@ConditionalOnProperty(prefix = "rabbitMq", name = "host", matchIfMissing = false)
public class RabbitMqServiceImpl implements MessageQueueService {
    private static final Logger LOGGER = LoggerFactory.getLogger(RabbitMqServiceImpl.class);
    private static final String DEFAULTEXCHANGE = "defaultExchange";
    private static final String CHARSET = "UTF-8";

    public RabbitMqServiceImpl() {
        LOGGER.info(">>> 实例化{}服务", "RabbitMqServiceImpl");
    }

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public void sendMessageToMessageQueue(String queueName, String messageId, String messageBody) {
        try {
            RabbitAdmin admin = new RabbitAdmin(rabbitTemplate.getConnectionFactory());

            //声明队列
            Queue queue = new Queue(queueName);
            admin.declareQueue(queue);
            //声明交换器
            DirectExchange directExchange = new DirectExchange(DEFAULTEXCHANGE);
            admin.declareExchange(directExchange);
            //绑定队列与交换器
            admin.declareBinding(BindingBuilder.bind(queue).to(directExchange).with(queueName));

            MessageProperties messageProperties = new MessageProperties();
            messageProperties.setHeader("messageId", messageId);
            Message message = new Message(messageBody.getBytes(CHARSET), messageProperties);
            //发送消息
            rabbitTemplate.setExchange(DEFAULTEXCHANGE);
            rabbitTemplate.setQueue(queueName);
            rabbitTemplate.send(message);

            LOGGER.info(">>> 发送消息到mq 队列:{},消息内容:{}", queueName, messageBody);
        } catch (Exception e) {
            throw new TransactionMessageException(e);
        }
    }
}
